package com.atguigu.spring5.proxy;

import com.atguigu.spring5.dao.IUserDao;
import com.atguigu.spring5.dao.impl.UserDaoImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * @author : wenchao.long
 * @date : Created in 2020/10/29 16:21 周四
 * @description :
 */
public class JdkProxy {

    public static void main(String[] args) {
        Class<?>[] interfaces = {IUserDao.class};
        IUserDao userDao = new UserDaoImpl();
        // 创建接口实现类代理对象
        IUserDao dao = (IUserDao) Proxy.newProxyInstance(JdkProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
        System.out.println("result:" + dao.add(1, 2));
        System.out.println("result:" + dao.update("143902392054393"));
    }
}

/**
 * 创建代理对象代码
 */
class UserDaoProxy implements InvocationHandler {

    // 1. 因为创建的是UserDaoImpl的代理对象 就需要把UserDaoImpl传递过来

    private final Object obj;

    public UserDaoProxy(Object obj) {
        this.obj = obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 增强的逻辑

        // 方法之前
        System.out.println("方法之前执行..." + method.getName() + ":传递的参数..." + Arrays.toString(args));

        String add = "add";
        String update = "update";

        if (add.equals(method.getName())) {
            StringBuffer sb = new StringBuffer();
            for (Object arg : args) {
                sb.append(arg);
            }
            System.out.println(sb);
        }
        if (update.equals(method.getName())) {
            StringBuffer sb = new StringBuffer();
            for (Object arg : args) {
                sb.append(arg);
                System.out.println(sb.reverse());
            }
        }

        // 被增强的方法执行
        Object res = method.invoke(obj, args);

        // 方法之后
        System.out.println("方法之后执行..." + obj);

        return res;
    }
}
